import 'package:flutter/material.dart';
import '../models/contact_model.dart';
import '../models/repair_order_model.dart';
import 'storage_service.dart';

/// 应用状态管理服务
/// 使用Provider进行全局状态管理
class AppStateService extends ChangeNotifier {
  String? _currentUserId;
  String? _currentUserTel;
  String? _currentUsername;
  bool _isLoggedIn = false;
  List<Contact> _contacts = [];
  List<RepairOrder> _repairOrders = [];
  bool _isLoading = false;
  String? _errorMessage;

  // Getters
  String? get currentUserId => _currentUserId;
  String? get currentUserTel => _currentUserTel;
  String? get currentUsername => _currentUsername;
  bool get isLoggedIn => _isLoggedIn;
  List<Contact> get contacts => _contacts;
  List<RepairOrder> get repairOrders => _repairOrders;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;

  /// 初始化应用状态
  Future<void> init() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 从本地存储加载登录状态
      _isLoggedIn = await StorageService.getBool('is_logged_in') ?? false;
      
      if (_isLoggedIn) {
        // 加载用户信息
        _currentUserId = await StorageService.getString('user_id');
        _currentUserTel = await StorageService.getString('user_tel');
        _currentUsername = await StorageService.getString('username');
        
        if (_currentUserId == null || _currentUserTel == null) {
          _isLoggedIn = false;
          await StorageService.clear();
        }
      }
    } catch (e) {
      _errorMessage = '初始化失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 用户登录
  Future<void> login(String userId, String userTel, String username, String password) async {
    _currentUserId = userId;
    _currentUserTel = userTel;
    _currentUsername = username;
    _isLoggedIn = true;
    
    // 保存到本地存储
    await StorageService.saveString('user_id', userId);
    await StorageService.saveString('user_tel', userTel);
    await StorageService.saveString('username', username);
    await StorageService.saveString('user_password', password);
    await StorageService.saveBool('is_logged_in', true);
    
    notifyListeners();
  }

  /// 用户登出
  Future<void> logout() async {
    _currentUserId = null;
    _currentUserTel = null;
    _currentUsername = null;
    _isLoggedIn = false;
    _contacts.clear();
    _repairOrders.clear();
    
    // 清除本地存储
    await StorageService.clear();
    
    notifyListeners();
  }

  /// 设置加载状态
  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 设置错误信息
  void setError(String? error) {
    _errorMessage = error;
    notifyListeners();
  }

  /// 清除错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  // ==================== 客户管理 ====================

  /// 添加客户
  void addContact(Contact contact) {
    _contacts.add(contact);
    notifyListeners();
  }

  /// 更新客户
  void updateContact(Contact contact) {
    final index = _contacts.indexWhere((c) => c.id == contact.id);
    if (index != -1) {
      _contacts[index] = contact;
      notifyListeners();
    }
  }

  /// 删除客户
  void removeContact(String contactId) {
    _contacts.removeWhere((c) => c.id == contactId);
    notifyListeners();
  }

  /// 设置客户列表
  void setContacts(List<Contact> contacts) {
    _contacts = contacts;
    notifyListeners();
  }

  /// 根据ID获取客户
  Contact? getContactById(String id) {
    try {
      return _contacts.firstWhere((c) => c.id == id);
    } catch (e) {
      return null;
    }
  }

  // ==================== 工单管理 ====================

  /// 添加工单
  void addRepairOrder(RepairOrder repairOrder) {
    _repairOrders.add(repairOrder);
    notifyListeners();
  }

  /// 更新工单
  void updateRepairOrder(RepairOrder repairOrder) {
    final index = _repairOrders.indexWhere((r) => r.id == repairOrder.id);
    if (index != -1) {
      _repairOrders[index] = repairOrder;
      notifyListeners();
    }
  }

  /// 删除工单
  void removeRepairOrder(String repairOrderId) {
    _repairOrders.removeWhere((r) => r.id == repairOrderId);
    notifyListeners();
  }

  /// 设置工单列表
  void setRepairOrders(List<RepairOrder> repairOrders) {
    _repairOrders = repairOrders;
    notifyListeners();
  }

  /// 根据ID获取工单
  RepairOrder? getRepairOrderById(String id) {
    try {
      return _repairOrders.firstWhere((r) => r.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 根据客户ID获取工单列表
  List<RepairOrder> getRepairOrdersByContactId(String contactId) {
    return _repairOrders.where((r) => r.owner == contactId).toList();
  }

  // ==================== 数据同步 ====================

  /// 刷新所有数据
  Future<void> refreshAllData() async {
    if (!_isLoggedIn || _currentUserId == null) return;

    setLoading(true);
    try {
      // 这里可以调用API服务刷新数据
      // 例如：await ApiService.getAllContacts(_currentUserTel!);
      // 例如：await ApiService.getAllRepairOrders(_currentUserTel!);
    } catch (e) {
      setError('刷新数据失败: $e');
    } finally {
      setLoading(false);
    }
  }

  /// 清除所有数据
  void clearAllData() {
    _contacts.clear();
    _repairOrders.clear();
    _errorMessage = null;
    notifyListeners();
  }
}